package com.rs.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.Date;
import java.util.UUID;

import com.rs.model.Document;


public class FileOperationsUtil {
	// 将文件转为字符串
	public static String getFileBase64(String file) {// 将文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(file);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		Encoder encoder = Base64.getEncoder();
		return encoder.encodeToString(data);// 返回Base64编码过的字节数组字符串
	}

	/**
	 * 
	 * @MethodName: getFilePath
	 * @Description: 将base64字符串转换为文件
	 * @author：fjc
	 * @date 2020-07-17 09:17:56 
	 * @param base64 base64d的文件
	 * @param rootPath 保存的父路径
	 * @param fileType 文件的后缀名
	 * @return String 文件的保存路径
	 */
	public static String getFilePath(String base64, String rootPath, String fileType) {
		// 判断是否存在目录
		File file = new File(rootPath);
		if (!file.exists()) {
			file.mkdirs();// 创建目录
		}
		rootPath = rootPath + "//" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_"
				+ UUID.randomUUID().toString() + fileType;//文件路径
		File img = new File(rootPath);
		Decoder decoder = Base64.getDecoder();
		try {
			// 解密
			byte[] b = decoder.decode(base64);
			// 处理数据
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(img);
			out.write(b);
			out.flush();
			out.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rootPath;
	}

	//文件下载
	public static boolean downloadFile(Document document, String newpath) {

		boolean flag = false;
		//新的文件
		File newFile = new File(newpath + "/" + document.getDo_name());
		if (!newFile.exists()) {
			try {
				newFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//System.out.println("文件不存在，新建成功！");
		}
		Decoder decoder = Base64.getDecoder();
		try {
			// 解密
			byte[] b = decoder.decode(document.getDo_base64());
			// 处理数据
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(newFile);
			out.write(b);
			out.flush();
			out.close();

			flag = true;

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}

}
